import 'dart:typed_data';
import 'package:image_compression/image_compression.dart';

class DnpDecompressionUtils {
  /// 压缩图片
  /// [imageBytes] 原始图片字节数据（List<int> 类型）
  /// 返回压缩后的图片字节数据，目标大小不超过500KB
  static Future<Uint8List> compressImage(List<int> imageBytes) async {
    const int targetSizeKB = 500;
    const int targetSizeBytes = targetSizeKB * 1024;

    // 如果图片已经小于500KB，直接返回
    if (imageBytes.length <= targetSizeBytes) {
      return Uint8List.fromList(imageBytes);
    }

    // 将 List<int> 转换为 Uint8List
    final imageData = imageBytes is Uint8List 
        ? imageBytes 
        : Uint8List.fromList(imageBytes);

    // 计算压缩质量，从高质量开始尝试
    int quality = 95;
    Uint8List compressedBytes = imageData;

    while (quality >= 10) {
      // 使用 image_compression 插件进行压缩
      final input = ImageFile(
        rawBytes: imageData,
        filePath: '',
      );

      final config = Configuration(
        outputType: OutputType.jpg,
        jpgQuality: quality,
      );

      final output = await compressInQueue(
        ImageFileConfiguration(input: input, config: config),
      );

      compressedBytes = output.rawBytes;

      // 如果压缩后的大小满足要求，则返回
      if (compressedBytes.length <= targetSizeBytes) {
        break;
      }

      // 降低质量继续压缩
      quality -= 10;
    }

    return compressedBytes;
  }
}